package com.wang.demo.application.handler;

import com.wang.demo.protocol.message.GroupCreateRequestMessage;
import com.wang.demo.protocol.message.GroupCreateResponseMessage;
import com.wang.demo.service.GroupSession;
import com.wang.demo.service.factory.GroupSessionFactory;
import com.wang.demo.service.pojo.Group;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;
import java.util.Set;

/**
 * @author: Jeffrey
 * @date: 2022/01/20/8:16
 * @description:
 */
@ChannelHandler.Sharable
public class GroupCreateRequestMessageHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupCreateRequestMessage msg) throws Exception {

        String name = msg.getGroupName();
        Set<String> members = msg.getMembers();
        /*获取到群组的会话管理器*/
        GroupSession session = GroupSessionFactory.getGroupSession();
        /*将群组注册到会话管理器*/
        Group group = session.createGroup(name,members);

        /*不存在则创建成功返回null，存在则返回已存在的group 对象*/
        if (group == null){
            /*name 不重复，群组创建成功*/
            ctx.writeAndFlush(new GroupCreateResponseMessage(true,"群组创建成功"));
            List<Channel> channels = session.getMembersChannel(name);
            channels.stream().forEach((channel) ->{
                channel.writeAndFlush(new GroupCreateResponseMessage(true,"您已被拉入"+name));
            });
        }else{
            /*name 重复创建失败*/
            ctx.writeAndFlush(new GroupCreateResponseMessage(false,name+"已存在"));
        }
    }
}
